﻿using System;
using UnityEngine;
using UnityEngine.EventSystems;

public class Joystick
{
    public Action<Vector2> onMoveDir;
    public Action onMoveEnd;

    GameObject _root;

    RectTransform _innerBall;
    RectTransform _outBall;

    float _radius= 0;
    Vector2 _centerPos;
    Vector2 _dir;

    public Joystick()
    {
        //_root = ResMgr.instance.GetInstance("UI/FightUI/Joystick");
        _root = UIManager.instance.Add("UI/FightUI/Joystick", UILayer.FightUI);

        _outBall = _root.Find<RectTransform>("bg");
        _innerBall = _root.Find<RectTransform>("bg/inner");

        //
        _radius = _outBall.rect.width * 0.5f;
        _centerPos = new Vector2(0, 0);


        var touchEx = _outBall.GetComponent<TouchRotate>();

        touchEx.DragCallback = onDrag;
        touchEx.PointDownCallback = onPointDown;
        touchEx.PointUpCallback = onPointUp;

        TimerMgr.instance.CreateTimer(0.1f, -1, onLoop);

    }

    private void onLoop()
    {
        //小球在中心店的时候不用移动
        if (_dir == Vector2.zero)
        {
            return;
        }
        if (onMoveDir != null)
        {
            onMoveDir(_dir);
        }
    }

    private void onPointUp(PointerEventData eventData)
    {
        _dir = Vector2.zero;
        if (onMoveEnd != null)
        {
            onMoveEnd();
        }
        _innerBall.localPosition = _centerPos;
    }

    private void onPointDown(PointerEventData eventData)
    {
        onDrag(eventData);
    }

    private void onDrag(PointerEventData eventData)
    {
        Vector2 targetpos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(_outBall, eventData.position, eventData.pressEventCamera, out targetpos);

        var dir = targetpos - _centerPos;
        _dir = dir.normalized;
        _innerBall.GetComponent<RectTransform>().localPosition = _dir * Mathf.Min(dir.magnitude, _radius);

        if (onMoveDir != null)
        {
            onMoveDir(_dir);
        }

    }
}

